
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class NeimengguNmgzzqbtskdlqrmzfD231Policy(BaseTaxPolicySpider):
    name = "neimenggu_nmgzzqbtskdlqrmzf_d231_policy"

    province: str = "内蒙古自治区"  # 取表格
    city: str = "包头市"  # 取表格
    county: str = "昆都仑区"  # 取表格
    park: str = "None"  # 取表格
    source: str = "内蒙古自治区包头市昆都仑区人民政府"  # 取表格 同一个来源合并
    url: str = "https://www.kdl.gov.cn/xzgfxwjk?type=1"  # 注明入口网址，以便后续排错
    host = url.split('.gov.cn')[0] + '.gov.cn'

    def start_requests(self):
        callback = self.parse_list
        yield scrapy.Request(self.url, callback=callback)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
                "//div[@class='info zfxxgk_ml_container2']//td//a[contains(@href, 'detail') or @title]/ancestor::td[string-length(string(.))>=5]"):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            print(item['source_url'])
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            pages = response.xpath("//div[@id='pagination']").re_first(r"""共计(\d+)页""") or 0
            print(f"{response.url} {pages}")
            for page_num in range(1, int(pages)):
                url = f"{response.url}" + f'?pageNum={page_num}&pageSize=8'
                yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl neimenggu_nmgzzqbtskdlqrmzf_d231_policy".split())
